//
//  DHCommerController.m
//  精品酒店
//
//  Created by DIANGHONG on 2018/5/16.
//  Copyright © 2018年 DIANGHONG. All rights reserved.
//

#import "DHCommerController.h"
#import "DHCommerFooterView.h"
#import "DHStoreLevel.h"
@interface DHCommerController ()<UITableViewDelegate,CZPickerViewDelegate,CZPickerViewDataSource,UIActionSheetDelegate, UIImagePickerControllerDelegate,UINavigationControllerDelegate,CLLocationManagerDelegate>
@property (weak, nonatomic) IBOutlet UITextField *companyTxtField;
@property (weak, nonatomic) IBOutlet UIButton *provinceButton;
@property (weak, nonatomic) IBOutlet UIButton *cityButton;
@property (weak, nonatomic) IBOutlet UIButton *regionButton;
@property (weak, nonatomic) IBOutlet UITextField *addrTxtField;
@property (weak, nonatomic) IBOutlet UITextField *nameTxtField;
@property (weak, nonatomic) IBOutlet UITextField *phoneTxtField;
@property (weak, nonatomic) IBOutlet UITextField *emailTxtField;
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *postImgButtons;
@property (weak, nonatomic) IBOutlet UITextField *businessLicenNum;
@property (weak, nonatomic) IBOutlet UITextField *businessScope;
@property (weak, nonatomic) IBOutlet UITextField *bankName;
@property (weak, nonatomic) IBOutlet UITextField *bankAccount;
@property (weak, nonatomic) IBOutlet UITextField *subBankName;
@property (weak, nonatomic) IBOutlet UITextField *subBankNumber;
@property (weak, nonatomic) IBOutlet UITextField *bankAddr;
@property (weak, nonatomic) IBOutlet UITextField *merchantAccount;
@property (weak, nonatomic) IBOutlet UITextField *storeNameTxtField;
@property (weak, nonatomic) IBOutlet UIButton *storeLevelButton;

@property(nonatomic,strong) UIImagePickerController *imagePicker; //声明全局的UIImagePickerController
@property(nonatomic ,strong)DHAreaModel *province; // 记录当前 区域模型
@property(nonatomic ,strong)CZPickerView *pickerView;
@property(nonatomic ,strong)DHAreaList *areaList; // 地区模型
@property(nonatomic ,strong)UIButton *currentImgBtn; // 记录当前选中按钮
@property(nonatomic ,strong)DHAreaModel *province_model;
@property(nonatomic ,strong)DHAreaModel *city_model;
@property(nonatomic ,strong)DHAreaModel *region_model;
@property(nonatomic ,strong)DHStoreLevel *storeModel; // 记录选中店铺等级
@property(nonatomic ,assign)BOOL isStoreLevelList;
@property(nonatomic ,strong)NSArray<DHStoreLevel *> *storeLevelList;


@property (nonatomic,strong ) CLLocationManager *locationManager;//定位服务
@property (nonatomic,copy) NSString *currentCity;   //城市
@property (nonatomic,copy) NSString *strLatitude;   //经度
@property (nonatomic,copy) NSString *strLongitude;  //维度
@end

@implementation DHCommerController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupNavBar];
    
    [self setupTableView];
    
    [self loadAreaData];
    
    [self loadStoreLevelList];
    
    [self locatemap];
}

- (void)locatemap{
    
    if ([CLLocationManager locationServicesEnabled]) {
        _locationManager = [[CLLocationManager alloc]init];
        _locationManager.delegate = self;
        [_locationManager requestAlwaysAuthorization];
        _currentCity = [[NSString alloc]init];
        [_locationManager requestWhenInUseAuthorization];
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        _locationManager.distanceFilter = 5.0;
        [_locationManager startUpdatingLocation];
    }
}

#pragma mark - 定位失败
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请在设置中打开定位" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *ok = [UIAlertAction actionWithTitle:@"打开定位" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *settingURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication]openURL:settingURL];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:cancel];
    [alert addAction:ok];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - 定位成功
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    
    [_locationManager stopUpdatingLocation];
    CLLocation *currentLocation = [locations lastObject];
    CLGeocoder *geoCoder = [[CLGeocoder alloc]init];
    //当前的经纬度
    NSLog(@"当前的经纬度 %f,%f",currentLocation.coordinate.latitude,currentLocation.coordinate.longitude);
    
    self.strLongitude = [NSString stringWithFormat:@"%f",currentLocation.coordinate.longitude];
    self.strLatitude =  [NSString stringWithFormat:@"%f",currentLocation.coordinate.latitude];;
    //这里的代码是为了判断didUpdateLocations调用了几次 有可能会出现多次调用 为了避免不必要的麻烦 在这里加个if判断 如果大于1.0就return
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        //地理反编码 可以根据坐标(经纬度)确定位置信息(街道 门牌等)
        [geoCoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            if (placemarks.count >0) {
                CLPlacemark *placeMark = placemarks[0];
                self->_currentCity = placeMark.locality;
                if (!self->_currentCity) {
                    self->_currentCity = @"无法定位当前城市";
                }
                //看需求定义一个全局变量来接收赋值
                //            NSLog(@"当前国家 - %@",placeMark.country);//当前国家
                NSLog(@"当前城市 - %@",self->_currentCity);//当前城市
               // self.leftNavButton.titleLabel.text = self->_currentCity;
                //[self.addrBtn setTitle:self->_currentCity forState:UIControlStateNormal];
                //            NSLog(@"当前位置 - %@",placeMark.subLocality);//当前位置
                //            NSLog(@"当前街道 - %@",placeMark.thoroughfare);//当前街道
                //            NSLog(@"具体地址 - %@",placeMark.name);//具体地址
                NSString *message = [NSString stringWithFormat:@"%@,%@,%@,%@,%@",placeMark.country,self->_currentCity,placeMark.subLocality,placeMark.thoroughfare,placeMark.name];
                
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:message delegate:self cancelButtonTitle:nil otherButtonTitles:@"好", nil];
                //            [alert show];
            }else if (error == nil && placemarks.count){
                
                NSLog(@"NO location and error return");
            }else if (error){
                
                NSLog(@"loction error:%@",error);
            }
        }];
    });
   // [self loadHomeTaskListWithPullUP:NO];
}
#pragma mark: - 店铺等级按钮监听
- (IBAction)selectedStoreBtn:(UIButton *)sender
{
    self.isStoreLevelList = YES;
    
    self.pickerView = [[CZPickerView alloc] initWithHeaderTitle:@"请选择店铺等级"
                                              cancelButtonTitle:@"取消"
                                             confirmButtonTitle:@"确认"];
    
    self.pickerView.needFooterView = true;
    self.pickerView.delegate = self;
    self.pickerView.dataSource = self;
    [self.pickerView show];
}
#pragma mark: - 扫描件上传按钮监听 （营业执照、银行）
- (IBAction)postImgBtnClick:(UIButton *)sender
{
    //self.currentImgBtn.selected = false;
    sender.selected = YES;
    self.currentImgBtn = sender;
    
    //自定义消息框
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"选择" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册选择", nil];
    sheet.tag = 2550;
    //显示消息框
    [sheet showInView:self.view];
}
- (void)postInfoToServces
{
    NSMutableArray *imgList = [NSMutableArray array];
    // 扫描件
    [self.postImgButtons enumerateObjectsUsingBlock:^(UIButton *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.currentImage) {[imgList addObject:obj.currentImage];}
    }];
    if (!(imgList.count >= 2)) {[SVProgressHUD showInfoWithStatus:@"请上传扫描件"];return;}
    
    // 公司名称
    if (!self.companyTxtField.hasText)
    {[SVProgressHUD showInfoWithStatus:@"请输入公司名称"];return;}
    
    // 所在地
    if ([self.provinceButton.currentTitle isEqualToString:@"省份"] ||
        [self.cityButton.currentTitle isEqualToString:@"城市"] ||
        [self.regionButton.currentTitle isEqualToString:@"区"]
    ) {[SVProgressHUD showInfoWithStatus:@"请选择所在地"];return;}
    
    //详细地址
    if (!self.addrTxtField.hasText) {[SVProgressHUD showInfoWithStatus:@"请输入详细地址"];return;}
    
    // 姓名
    if (!self.nameTxtField.hasText) {[SVProgressHUD showInfoWithStatus:@"请输入联系人姓名"];return;}
    
    // 电话
    if (!self.phoneTxtField.hasText) {[SVProgressHUD showInfoWithStatus:@"请输入联系人电话"];return;}
    
    // 邮箱
    if (!self.emailTxtField.hasText) {[SVProgressHUD showInfoWithStatus:@"请输入电子邮箱"];return;}
    
    // 营业执照号
    if (!self.businessLicenNum.hasText) {[SVProgressHUD showInfoWithStatus:@"请输入营业执照号"];return;}
    
    // 经营范围
    if (!self.businessScope.hasText) {[SVProgressHUD showInfoWithStatus:@"请输入经营范围"];return;}
    
    // 银行开户名
    if (!self.bankName.hasText) {[SVProgressHUD showInfoWithStatus:@"请输入银行开户名"];return;}

    // 银行账号
    if (!self.bankAccount.hasText) {[SVProgressHUD showInfoWithStatus:@"请输入银行账号"];return;}
    
    // 支行名称
    if (!self.subBankName.hasText) {[SVProgressHUD showInfoWithStatus:@"请输入支行名称"];return;}
    
    // 支行联行号
    if (!self.subBankNumber.hasText) {[SVProgressHUD showInfoWithStatus:@"请输入支行联行号"];return;}

    // 银行所在地
    if (!self.bankAddr.hasText) {[SVProgressHUD showInfoWithStatus:@"请输入支行名称"];return;}

    // 商家商户
    if (!self.merchantAccount.hasText) {[SVProgressHUD showInfoWithStatus:@"请输入支行名称"];return;}
    
    // 店铺名称
    if (!self.storeNameTxtField.hasText) {[SVProgressHUD showInfoWithStatus:@"请输入支行名称"];return;}

    // 店铺等级
    if ([self.storeLevelButton.currentTitle isEqualToString:@"请选择"]) {[SVProgressHUD showInfoWithStatus:@"请选择店铺等级"];return;}
    
    NSMutableDictionary *dictM = [NSMutableDictionary dictionary];
    dictM[@"key"] = DHNetworkManager.shareManager.userAccount.key;
    dictM[@"company_name"] = self.companyTxtField.text;
    dictM[@"seller_name"] = self.merchantAccount.text;
    dictM[@"store_name"] = self.storeNameTxtField.text;
    dictM[@"sg_id"] = self.storeModel.sg_id;
    dictM[@"sg_name"] = self.storeModel.sg_name;
    dictM[@"company_province_id"] = self.province_model.area_id;
    dictM[@"company_city_id"] = self.city_model.area_id;
    dictM[@"company_area_id"] = self.region_model.area_id;
    dictM[@"company_address"] = [NSString stringWithFormat:@"%@%@%@",self.province_model.area_name,self.city_model.area_name,self.region_model.area_name];
    dictM[@"company_address_detail"] = self.addrTxtField.text;
    dictM[@"company_points"] = @"";
    dictM[@"contacts_name"] = self.nameTxtField.text;
    dictM[@"contacts_phone"] = self.phoneTxtField.text;
    dictM[@"contacts_email"] = self.emailTxtField.text;
    dictM[@"business_sphere"] = self.businessScope.text;
    dictM[@"business_licence_number"] = self.businessLicenNum.text;
    dictM[@"settlement_bank_account_number"] = self.bankAccount.text;
    dictM[@"settlement_bank_account_name"] = self.bankName.text;
    dictM[@"bank_name"] = self.subBankName.text;
    dictM[@"bank_code"] = self.subBankNumber.text;
    dictM[@"bank_address"] = self.bankAddr.text;
    dictM[@"company_points"] = [NSValue valueWithCGPoint:CGPointMake(self.strLatitude.floatValue, self.strLongitude.floatValue)];
    [self postUserImageFormDateWithParam:dictM.copy licenseList:imgList.copy];

}
#pragma mark -- 上传头像Data
- (NSString*)returnFielName{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat =@"yyyyMMddHHmmss";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
    return fileName;
}
- (void)postUserImageFormDateWithParam:(NSDictionary *)param licenseList:(NSArray *)licenseList{
    
    //    NSString * sexString =[self.sexSelectButton.titleLabel.text isEqualToString:@"男"]?@"1":@"0";
    //
    //    NSDictionary *dict = @{@"key":[UserManager shareUser].key, @"mobile":self.phoneTextField.text,@"level_id":self.VIP_id,@"level_name":self.rankTextField.text,@"tuijian_member_name":self.recommenTextField.text,@"auth_name":self.realNameTextField.text,@"auth_card":self.idCarTextField.text,@"auth_sex":sexString};
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/json",@"text/plain", nil];
    // 营业执照上传
    NSData *imgData1 = nil;
    imgData1 =UIImageJPEGRepresentation(licenseList.firstObject,1);
    if ([imgData1 length]/1024<=100) {
        imgData1 =UIImageJPEGRepresentation(licenseList.firstObject,1);

    }else{

        imgData1 =UIImageJPEGRepresentation([self compressImage:licenseList.firstObject toByte:100*1024],0.5);
    }
    // 联行号上传
    NSData *imgData2 = nil;
    imgData2 =UIImageJPEGRepresentation(licenseList.lastObject,1);
    if ([imgData2 length]/1024<=100) {
        imgData2 =UIImageJPEGRepresentation(licenseList.lastObject,1);

    }else{

        imgData2 =UIImageJPEGRepresentation([self compressImage:licenseList.lastObject toByte:100*1024],0.5);
    }

    NSArray *nameArray = @[@"business_licence_number_electronic",@"bank_licence_electronic"];
    [manager POST:@"http://jpjd.cnaite.cn/mobile/index.php?act=seller&op=save"
       parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
           
           
           
           [formData appendPartWithFileData:imgData1
                                       name:nameArray[0]
                                   fileName:[self returnFielName]
                                   mimeType:@"image/jpeg"];
           [formData appendPartWithFileData:imgData2
                                       name:nameArray[1]
                                   fileName:[self returnFielName]
                                   mimeType:@"image/jpeg"];

           
           
           
       } progress:nil
          success:^(NSURLSessionTask *task, id responseObject) {
              
              //  NSString * errorStr;
              NSString *temp = responseObject[@"datas"];
              
              if (temp.boolValue) {
                  NSLog(@"...");
                  [SVProgressHUD showSuccessWithStatus:@"提交成功"];
                  [self.navigationController popToRootViewControllerAnimated:true];
              }else{
                  [SVProgressHUD showSuccessWithStatus:@"提交失败"];
                  [self.navigationController popToRootViewControllerAnimated:true];
              }
              
              
          }
     
          failure:^(NSURLSessionTask *task, NSError *error) {
              NSLog(@"error:%@", error);
              
              
              
          }];
    
    
}

#pragma mark: - 压缩图像
- (UIImage *)compressImage:(UIImage *)image toByte:(NSUInteger)maxLength {
    // Compress by quality
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    
    
    if (data.length < maxLength) return image;
    
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(image, compression);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    
    UIImage *resultImage = [UIImage imageWithData:data];
    
    if (data.length < maxLength)
        
        return resultImage;
    
    // Compress by size
    NSUInteger lastDataLength = 0;
    while (data.length > maxLength && data.length != lastDataLength) {
        lastDataLength = data.length;
        CGFloat ratio = (CGFloat)maxLength / data.length;
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
                                 (NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank
        UIGraphicsBeginImageContext(size);
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        data = UIImageJPEGRepresentation(resultImage, compression);
        
    }
    
    return resultImage;
}
#pragma mark: - 省份按钮监听
- (IBAction)provinceBtnClick:(UIButton *)sender
{
    [self.view endEditing:YES];
    
    self.province = nil;
    self.areaList = nil;
    [self loadAreaData];
    //NSLog(@"%@",sender.currentTitle);
    self.pickerView = [[CZPickerView alloc] initWithHeaderTitle:@"省份"
                                              cancelButtonTitle:@"取消"
                                             confirmButtonTitle:@"确认"];
    
    self.pickerView.needFooterView = true;
    self.pickerView.delegate = self;
    self.pickerView.dataSource = self;
    [self.pickerView show];
}
#pragma mark: - 城市按钮监听
- (IBAction)cityBtnClick:(UIButton *)sender
{
    [self.view endEditing:YES];

    if (!self.province) {
        [SVProgressHUD showInfoWithStatus:@"请先选择省份"];
        return;
    }
    self.pickerView = [[CZPickerView alloc] initWithHeaderTitle:@"城市"
                                              cancelButtonTitle:@"取消"
                                             confirmButtonTitle:@"确认"];
    
    self.pickerView.needFooterView = true;
    self.pickerView.delegate = self;
    self.pickerView.dataSource = self;
    [self.pickerView show];
}
#pragma mark: - 加载店铺等级列表
- (void)loadStoreLevelList
{
    NSString *url = @"http://jpjd.cnaite.cn/mobile/index.php?act=seller&op=index";
    NSMutableDictionary *dictM = [NSMutableDictionary dictionary];
    dictM[@"key"] = DHNetworkManager.shareManager.userAccount.key;
    [DHNetworkManager.shareManager requestWithMethod:MethodPost UrlString:url params:dictM.copy completion:^(id json, BOOL isSuccess)
     {
         if (!isSuccess) {
             [SVProgressHUD showErrorWithStatus:@"请检查网络"];
             return ;
         }
         //NSLog(@"%@",json[@"datas"][@"grade_list"]);
         NSDictionary *dict = json[@"datas"][@"grade_list"];
         
        // NSLog(@"%@",dict.allKeys);
         NSMutableArray *arrayM = [NSMutableArray arrayWithCapacity:5];
         for (NSString *key in dict.allKeys)
         {
             if (!(key.length > 0)) {
                 continue;
             }
             [arrayM addObject:dict[key]];
         }
         self.storeLevelList = [NSArray yy_modelArrayWithClass:[DHStoreLevel class] json:arrayM.copy];
         
    }];
}
#pragma mark -实现图片选择器代理-（上传图片的网络请求也是在这个方法里面进行，这里我不再介绍具体怎么上传图片）
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^{}];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage]; //通过key值获取到图片
    
    //上传图片到服务器--在这里进行图片上传的网络请求，这里不再介绍
    //  ......
    [self.currentImgBtn setImage:image forState:UIControlStateNormal];
}
#pragma mark -消息框代理实现-
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (actionSheet.tag == 2550) {
        NSUInteger sourceType = 0;
        // 判断系统是否支持相机
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            imagePickerController.delegate = self; //设置代理
            imagePickerController.allowsEditing = YES;
            imagePickerController.sourceType = sourceType; //图片来源
            if (buttonIndex == 0) {
                //拍照
                sourceType = UIImagePickerControllerSourceTypeCamera;
                imagePickerController.sourceType = sourceType;
                [self presentViewController:imagePickerController animated:YES completion:nil];
                
                
            }else if (buttonIndex == 1) {
                //相册
                sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                imagePickerController.sourceType = sourceType;
                [self presentViewController:imagePickerController animated:YES completion:nil];
                
            }else if (buttonIndex == 2){
                
                return;
            }
        }else {
            sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            imagePickerController.sourceType = sourceType;
            [self presentViewController:imagePickerController animated:YES completion:nil];
        }
    }
}
#pragma mark: - 区按钮监听
- (IBAction)regionBtnClick:(UIButton *)sender
{
    [self.view endEditing:YES];

    if (!self.province) {
        [SVProgressHUD showErrorWithStatus:@"请选择城市"];
        return;
    }
    self.pickerView = [[CZPickerView alloc] initWithHeaderTitle:@"地区"
                                              cancelButtonTitle:@"取消"
                                             confirmButtonTitle:@"确认"];
    
    self.pickerView.needFooterView = true;
    self.pickerView.delegate = self;
    self.pickerView.dataSource = self;
    [self.pickerView show];
}

#pragma mark: - CZPickerViewDataSource
- (NSInteger)numberOfRowsInPickerView:(CZPickerView *)pickerView
{
    return self.isStoreLevelList ? self.storeLevelList.count : self.areaList.list.count;
}
- (NSAttributedString *)czpickerView:(CZPickerView *)pickerView
               attributedTitleForRow:(NSInteger)row
{
    NSString *str = self.isStoreLevelList ? self.storeLevelList[row].sg_name : [self.areaList.list[row] area_name];
    return [[NSAttributedString alloc] initWithString: str];
}

#pragma mark: - CZPickerViewDelegate
- (void)czpickerView:(CZPickerView *)pickerView
didConfirmWithItemAtRow:(NSInteger)row
{
    if (self.isStoreLevelList) {
        self.isStoreLevelList = false;
        self.storeModel = self.storeLevelList[row];
        [self.storeLevelButton setTitle:self.storeLevelList[row].sg_name forState:UIControlStateNormal];
        return;
    }
    [self setAreaButtonDataSourceWithDeep:self.areaList.deep row:row];
    self.province = self.areaList.list[row];
    self.areaList = nil;
    [self loadAreaData];
}
- (void)czpickerViewDidClickCancelButton:(CZPickerView *)pickerView
{
    if (self.isStoreLevelList) {
        self.isStoreLevelList = false;
    }
}
#pragma mark: - 设置地区按钮文字
- (void)setAreaButtonDataSourceWithDeep:(NSString *)deep row:(NSInteger)row
{
    DHAreaModel *areaModel = self.areaList.list[row];
    switch (deep.intValue) {
        case 1: // 省份
            [self.provinceButton setTitle:areaModel.area_name forState:UIControlStateNormal];
            self.province_model = areaModel;
            break;
        case 2: // 城市
            [self.cityButton setTitle:areaModel.area_name forState:UIControlStateNormal];
            self.city_model = areaModel;

            break;
        default:
            [self.regionButton setTitle:areaModel.area_name forState:UIControlStateNormal];
            self.region_model = areaModel;
            break;
    }
}

#pragma mark: - 设置TableView
- (void)setupTableView
{
    DHCommerFooterView *footerView = [DHCommerFooterView footerViewWithFrame:CGRectMake(0, 0, kScreenWidth, 88)];
    footerView.postButtonClick =
    ^{
        //FIXME: - 未实现提交按钮功能
        [self postInfoToServces];
    };
    self.tableView.tableFooterView = footerView;
    
}

#pragma mark: - 加载地区数据
- (void)loadAreaData
{
    NSString *url = @"http://jpjd.cnaite.cn/mobile/index.php?act=index&op=getArea";
    
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    params[@"area_id"] = self.province.area_id;
    
    [DHNetworkManager.shareManager requestWithMethod:MethodGet
                                           UrlString:url
                                              params:params.copy
                                          completion:^(id json, BOOL isSuccess)
     {
         if (!isSuccess)
         {
             [SVProgressHUD showErrorWithStatus:@"请检查网络"];
             return ;
         }
         
         self.areaList = [DHAreaList yy_modelWithJSON:json[@"datas"]];
         
         [self.pickerView reloadData];
     }];
    
}
#pragma mark: - 设置导航栏
- (void)setupNavBar
{
    self.navigationController.navigationBar.hidden = false;
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:222.0f/255.0f green:60.0f/255.0f blue:50.0f/255.0f alpha:1];
    self.title = @"商家入驻";
    [self.navigationController.navigationBar setTintColor:UIColor.whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont systemFontOfSize:17],
       NSForegroundColorAttributeName:[UIColor whiteColor]}];
   
}

#pragma mark: - 实例化方法
+ (instancetype)commerContronller
{
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"DHCommerController" bundle:nil];
    DHCommerController *vc = [sb instantiateViewControllerWithIdentifier:@"DHCommerID"];
    return vc;
}

#pragma mark: - UITableViewDelegate
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return [self creatHeaderViewWithSection:section];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 44;
}
#pragma mark: - 创建headerView
- (UIView *)creatHeaderViewWithSection:(NSInteger)section
{
    NSString *headerTitle;
    switch (section)
    {
        case 0:
            headerTitle = @"    公司及联系人信息";
            break;
        case 1:
            headerTitle = @"    营业执照信息";
            break;
        case 2:
            headerTitle = @"    开户银行信息";
            break;
        case 3:
            headerTitle = @"    经营信息";
            break;
    }
    UILabel *label = [[UILabel alloc] init];
    label.text = headerTitle;
    label.font = [UIFont systemFontOfSize:14];
    return label;
}
@end
